<?php
include("configAdmin.php");

require_once(BIB_ADODB);

require_once(FWK_CONTROL."ControlSmarty.class.php");
require_once(FWK_CONTROL."ControlSessao.class.php");
require_once(FWK_CONTROL."ControlDB.class.php");

require_once(BIB_PEARL);
require_once(BIB_SMARTY);
require_once(BIB_MAILER);

require_once(FWK_UTIL."FormataCampos.class.php");
require_once(FWK_UTIL."FormataDatas.class.php");
require_once(FWK_UTIL."FormataPost.class.php");
require_once(FWK_UTIL."FormataString.class.php");
require_once(FWK_UTIL."Debuga.class.php");
require_once(FWK_UTIL."Utf8Parsers.class.php");
require_once(FWK_UTIL."HttpUtil.class.php");

require_once(FWK_EXCEPTION."CustonException.class.php");
require_once(BIB_FWK."adodb/adodb-errorpear.inc.php");

require_once(PASTA_DAO."Categoria.class.php");
require_once(PASTA_DAO."Produto.class.php");
require_once(PASTA_DAO."Cliente.class.php");
require_once(PASTA_DAO."Usuario.class.php");
require_once(PASTA_DAO."Estado.class.php");
require_once(PASTA_DAO."Cidade.class.php");
require_once(PASTA_DAO."Orcamento.class.php");
require_once(PASTA_DAO."ProdutoOrcamento.class.php");
require_once(PASTA_DAO."Evento.class.php");

global $objCtrlSmarty;
global $objSessao;
global $objUsrSession;
global $menu;

//biblioteca de controle dos templates
$objCtrlSmarty = ControlSmarty::getSmarty();

//SESSAO
$objSessao = new ControlSessao();
$objUsrSession = $objSessao->getObjSessao(SESSAO_ADMIN);

//definição dos estilos do admin, se necessário acrescentar outro, apenas concatenar à string com \n no final.
$strCss = "<link rel=\"stylesheet\" type=\"text/css\" href=\"".URL_CSS."jquery.fancybox-1.3.4.css\" />\n";
$strCss .= "<link rel=\"stylesheet\" type=\"text/css\" href=\"".URL_CSS."forms/screen.css\" />\n";
$objCtrlSmarty->assign("CSS_SITE",$strCss);

$strJs = "<script type=\"text/javascript\" src=\"".URL_JS."jquery.js\"></script>\n";
$strJs .= "<script type=\"text/javascript\" src=\"".URL_JS."jquery.fancybox-1.3.4.pack.js\"></script>\n";
$strJs .= "<script type=\"text/javascript\" src=\"".URL_JS."jquery.maskedinput-1.1.4.pack.js\"></script>\n";
$strJs .= "<script type=\"text/javascript\" src=\"".URL_JS."forms/custom_jquery.js\"></script>\n";
$strJs .= "<script type=\"text/javascript\" src=\"".URL_JS."forms/jquery.pngFix.pack.js\"></script>\n";
$strJs .= "<script type=\"text/javascript\" src=\"".URL_JS."forms/ui.core.js\"></script>\n";
$strJs .= "<script type=\"text/javascript\" src=\"".URL_JS."forms/ui.checkbox.js\"></script>\n";
$strJs .= "<script type=\"text/javascript\" src=\"".URL_JS."jquery.meio.mask.min.js\"></script>\n";
$strJs .= "<script type=\"text/javascript\" src=\"".URL_JS."forms/jquery.bind.js\"></script>\n

<![if !IE 7]>

<!--  styled select box script version 1 -->
<script src=\"".URL_JS."forms/jquery.selectbox-0.5.js\" type=\"text/javascript\"></script>
<script type=\"text/javascript\">
jQuery(document).ready(function() {
	jQuery('.styledselect').selectbox({ inputClass: \"selectbox_styled\" });
});
</script>
 

<![endif]>

<!--  styled file upload script --> 
<script src=\"".URL_JS."forms/jquery.filestyle.js\" type=\"text/javascript\"></script>
<script type=\"text/javascript\" charset=\"utf-8\">
  jQuery(function() {
      jQuery(\"input.file_1\").filestyle({ 
          image: \"images/forms/choose-file.gif\",
          imageheight : 21,
          imagewidth : 78,
          width : 310
      });
  });
</script>

<!-- Custom jquery scripts -->
<script src=\"".URL_JS."forms/custom_jquery.js\" type=\"text/javascript\"></script>
 
<!-- Tooltips -->
<script src=\"".URL_JS."forms/jquery.tooltip.js\" type=\"text/javascript\"></script>
<script src=\"".URL_JS."forms/jquery.dimensions.js\" type=\"text/javascript\"></script>
<script type=\"text/javascript\">
jQuery(function() {
	jQuery('a.info-tooltip ').tooltip({
		track: true,
		delay: 0,
		fixPNG: true, 
		showURL: false,
		showBody: \" - \",
		top: -35,
		left: 5
	});
});
</script> 


<!--  date picker script -->
<link rel=\"stylesheet\" href=\"".URL_CSS."forms/datePicker.css\" type=\"text/css\" />
<script src=\"".URL_JS."forms/date.js\" type=\"text/javascript\"></script>
<script src=\"".URL_JS."forms/jquery.datePicker.js\" type=\"text/javascript\"></script>
<script type=\"text/javascript\" charset=\"utf-8\">
        jQuery(function()
{

// initialise the \"Select date\" link
jQuery('#date-pick')
	.datePicker(
		// associate the link with a date picker
		{
			createButton:false,
			startDate:'01/01/2005',
			endDate:'31/12/2020'
		}
	).bind(
		// when the link is clicked display the date picker
		'click',
		function()
		{
			updateSelects(jQuery(this).dpGetSelected()[0]);
			jQuery(this).dpDisplay();
			return false;
		}
	).bind(
		// when a date is selected update the SELECTs
		'dateSelected',
		function(e, selectedDate, jQuerytd, state)
		{
			updateSelects(selectedDate);
		}
	).bind(
		'dpClosed',
		function(e, selected)
		{
			updateSelects(selected[0]);
		}
	);
	
var updateSelects = function (selectedDate)
{
	var selectedDate = new Date(selectedDate);
	jQuery('#d option[value=' + selectedDate.getDate() + ']').attr('selected', 'selected');
	jQuery('#m option[value=' + (selectedDate.getMonth()+1) + ']').attr('selected', 'selected');
	jQuery('#y option[value=' + (selectedDate.getFullYear()) + ']').attr('selected', 'selected');
}
// listen for when the selects are changed and update the picker
jQuery('#d, #m, #y')
	.bind(
		'change',
		function()
		{
			var d = new Date(
						jQuery('#y').val(),
						jQuery('#m').val()-1,
						jQuery('#d').val()
					);
			jQuery('#date-pick').dpSetSelected(d.asString());
		}
	);

// default the position of the selects to today
var today = new Date();
updateSelects(today.getTime());

// and update the datePicker to reflect it...
jQuery('#d').trigger('change');
});
</script>
";
$strJs .= "<script type=\"text/javascript\" src=\"".URL_JS."acoesAdmin.js\"></script>\n";
$strJs .= "<script type=\"text/javascript\">jQuery(document).ready(function(){jQuery(document).pngFix( );});
</script>\n";
$objCtrlSmarty->assign("JS_SITE",$strJs);

//constantes depedentes
define("PADRAO_EXIBICAO", PE_ESTRUTURADA);

//título da pagina
$objCtrlSmarty->assign("TITULO_PAG",utf8_encode(TITULO_ADMIN));

//CRIAÇÃO DOS LINKS DE MENU
$menu["Index"] = array("url_basica"=>LINK_ADMIN."index.php", "menu"=>LINK_ADMIN."index.php");
$menu["CrudCategorias"] = array("url_basica" => LINK_ADMIN."CrudCategorias.php", "menu"=>LINK_ADMIN."CrudCategorias.php");
$menu["CrudProdutos"] = array("url_basica" => LINK_ADMIN."CrudProdutos.php", "menu"=>LINK_ADMIN."CrudProdutos.php");
$menu["CrudClientes"] = array("url_basica" => LINK_ADMIN."CrudClientes.php", "menu"=>LINK_ADMIN."CrudClientes.php");
$menu["CrudOrcamentos"] = array("url_basica" => LINK_ADMIN."CrudOrcamentos.php", "menu"=>LINK_ADMIN."CrudOrcamentos.php");
$menu["CrudEventos"] = array("url_basica" => LINK_ADMIN."CrudEventos.php", "menu"=>LINK_ADMIN."CrudEventos.php");

$menu["CrudUsuarios"] = array("url_basica" => LINK_ADMIN."CrudUsuarios.php", "menu"=>LINK_ADMIN."CrudUsuarios.php");
$menu["Contato"] = array("url_basica" => LINK_ADMIN."FormContato.php", "menu"=>LINK_ADMIN."FormContato.php");
$menu["Login"] = array("url_basica" => LINK_ADMIN."login.php", "menu"=>LINK_ADMIN."login.php" , "post" => "login.php?a=logar");
$menu["RecuperaSenha"] = array("url_basica" => LINK_ADMIN."login.php", "menu"=>LINK_ADMIN."login.php" , "post" => "login.php?a=recuperaSenha");
$menu["TrocaSenha"] = array("url_basica" => LINK_ADMIN."login.php", "menu"=>LINK_ADMIN."login.php" , "post" => "login.php?a=alteraSenha");
$menu["Logout"] = array("url_basica" => LINK_ADMIN."login.php", "menu"=>LINK_ADMIN."login.php" , "post" => "login.php?a=logout");
$PADRAO_SESSAO_EXPIRADA = LINK_ADMIN."login.php?msg=1";


$menu["CrudImpressao"] = array("url_basica" => LINK_ADMIN."CrudImpressao.php", "menu"=>LINK_ADMIN."CrudImpressao.php");

if(PADRAO_EXIBICAO == PE_CRIPTOGRAFADA){
	$menu["Login"] = array("url_basica" => LINK_ADMIN."login.php", "menu"=>LINK_ADMIN."login.php" , "post" => LINK_ADMIN."login.php?p=".base64_encode(serialize(array("a"=>"logar"))));
	$menu["RecuperaSenha"] = array("url_basica" => LINK_ADMIN."login.php", "menu"=>LINK_ADMIN."login.php" , "post" => LINK_ADMIN."login.php?p=".base64_encode(serialize(array("a"=>"recuperaSenha"))));
	$menu["TrocaSenha"] = array("url_basica" => LINK_ADMIN."login.php", "menu"=>LINK_ADMIN."login.php" , "post" => LINK_ADMIN."login.php?p=".base64_encode(serialize(array("a"=>"alteraSenha"))));
	$menu["Logout"] = array("url_basica" => LINK_ADMIN."login.php", "menu"=>LINK_ADMIN."login.php" , "post" => LINK_ADMIN."login.php?p=".base64_encode(serialize(array("a"=>"logout"))));
	
}elseif(PADRAO_EXIBICAO == PE_AMIGAVEL){
	$menu["Index"] = array("url_basica"=>LINK_ADMIN, "menu"=>LINK_ADMIN);
	$menu["CrudCategorias"] = array("url_basica" => LINK_ADMIN."categorias/", "menu"=>LINK_ADMIN."categorias/");
	$menu["CrudProdutos"] = array("url_basica" => LINK_ADMIN."produtos/", "menu"=>LINK_ADMIN."produtos/");
	$menu["CrudClientes"] = array("url_basica" => LINK_ADMIN."clientes/", "menu"=>LINK_ADMIN."clientes/");
	
	$menu["CrudUsuarios"] = array("url_basica" => LINK_ADMIN."usuarios/", "menu"=>LINK_ADMIN."usuarios/");
	$menu["Contato"] = array("url_basica" => LINK_ADMIN."contato/", "menu"=>LINK_ADMIN."contato/");
	$menu["Login"] = array("url_basica" => LINK_ADMIN."login/", "menu"=>LINK_ADMIN."login/", "post" => LINK_ADMIN."login/logar/");
	$menu["RecuperaSenha"] = array("url_basica" => LINK_ADMIN."login/", "menu"=>LINK_ADMIN."login/", "post" => LINK_ADMIN."login/recuperaSenha/");
	$menu["TrocaSenha"] = array("url_basica" => LINK_ADMIN."login/", "menu"=>LINK_ADMIN."login/", "post" => LINK_ADMIN."login/alteraSenha/");
	$menu["Logout"] = array("url_basica" => LINK_ADMIN."logout/", "menu"=>LINK_ADMIN."login/", "post" => LINK_ADMIN."logout/");
	$PADRAO_SESSAO_EXPIRADA = LINK_ADMIN."login/null/1/";
	
	$menu["CrudImpressao"] = array("url_basica" => LINK_ADMIN."impressao/", "menu"=>LINK_ADMIN."impressao/");
}

define("PADRAO_SESSAO_EXPIRADA", $PADRAO_SESSAO_EXPIRADA);
$objCtrlSmarty->assign("LINK_MENU",$menu);

//Variáveis
$objCtrlSmarty->assign("TITULO",TITULO_SITE);
$objCtrlSmarty->assign("CORPADRAO", "vinho");

$objCtrlSmarty->assign("NOME_USUARIO",$objUsrSession->getNomeUsuario());
$objCtrlSmarty->assign("TIPO_USUARIO",$objUsrSession->getGrupoUsuario());
$objCtrlSmarty->assign("ID_USUARIO",$objUsrSession->id_usuario);

$objCtrlSmarty->assign("DADO_ULTIMO_ACESSO",FormataDatas::getDataHora($objUsrSession->getUltimoAcesso()));

if(!empty($_COOKIE["home"])){
	$objCtrlSmarty->assign("NA_HOME",true);
	unset($_COOKIE["home"]);
}

//define o cabeçaho do admin
$objCtrlSmarty->assign("CABECALHO",$objCtrlSmarty->fetch(TPLS_FILE."admin/adminCabecalho.tpl"));

//define o menu do admin
$objCtrlSmarty->assign("MENU_ADMIN",$objCtrlSmarty->fetch(TPLS_FILE."admin/adminMenu.tpl"));

//define o rodape do admin
$objCtrlSmarty->assign("RODAPE",$objCtrlSmarty->fetch(TPLS_FILE."admin/adminRodape.tpl"));


if(isset($_GET["busca"]) || isset($_GET["p"])){
	$busca = addslashes($_GET["busca"]);
}
if(isset($_GET["p"])){
	$_GET = unserialize(base64_decode($_GET["p"]));
}
if(!empty($busca))
	$_POST["busca"] = $busca;

if((isset($_POST["NUM_ELEMENTOS_GRID"]) && (int)$_POST["NUM_ELEMENTOS_GRID"] > 0))
	$numElementosGrid = $_POST["NUM_ELEMENTOS_GRID"];
elseif((isset($_SESSION["NUM_ELEMENTOS_GRID"]) && (int)$_SESSION["NUM_ELEMENTOS_GRID"] > 0))
	$numElementosGrid = $_SESSION["NUM_ELEMENTOS_GRID"];
else
	$numElementosGrid = 10;
	
define("NUM_ELEMENTOS_GRID", $numElementosGrid);
$_SESSION["NUM_ELEMENTOS_GRID"] = $numElementosGrid; 

/**
 * Mensagens do sistema, adicionar aqui para o admin, para seguir o default no sistema
 */
if(isset($_GET["msg"])){
	$exibe = false;
	switch($_GET["msg"]){
		case 3:
			$objCtrlSmarty->assign("LABEL_MENS_SIS",MSG_CADASTRO_SUCESSO);
			$exibe = true;
			break;
		case 4:
			$objCtrlSmarty->assign("LABEL_MENS_SIS",MSG_EXCLUIDO_SUCESSO);
			$exibe = true;
			break;
		case 5:
			$objCtrlSmarty->assign("LABEL_MENS_SIS",MSG_CADASTRO_ERRO);
			$exibe = true;
			break;
		case 6:
			$objCtrlSmarty->assign("LABEL_MENS_SIS",MSG_FALECONOSCO_SUCESSO);
			$exibe = true;
			break;
	}
	if($exibe)
		$objCtrlSmarty->assign("MSG_SISTEMA",$objCtrlSmarty->fetch(TPLS_FILE."admin/adminMsg.tpl"));
}
$aux = explode(".", end(explode("/", $_SERVER['SCRIPT_FILENAME'])));
$class = $aux[0];

function confereSessao(){
	global $objUsrSession;
	if($objUsrSession->getIdUsuario() == 0){
		$_GET["pos1"] = $class;
		$_SESSION["tava"] = $_GET;
		HttpUtil::vaiPara(PADRAO_SESSAO_EXPIRADA);
	}
}

function getId($id = null){
	if($id == null){
		if(!isset($_GET["id"]))
			$id = '';
		else
			$id = intval(FormataString::retiraCharsInvalidos(trim($_GET["id"])));
	}else{
		$id = intval(FormataString::retiraCharsInvalidos(trim($id)));
	}
	
	if(!is_numeric($id) || $id == 0 || $id=="") 
		$id = null;
	return $id;
}

function setScriptMenu($nivel1, $nivel2 = false, $retorna = false){
	global $objCtrlSmarty;
	
	$strJsPag = '<script type="text/javascript">
		jQuery(document).ready(function(){
			jQuery(".'.$nivel1.'").addClass("current");	';
	if(!empty($nivel2))
		$strJsPag .= ' 
			jQuery(".'.$nivel1.' .select_sub").addClass("show");	 
			jQuery(".'.$nivel1.' .select_sub .'.$nivel2.'").addClass("sub_show");';	 
	$strJsPag .= ' 
		});
	</script>';
	if($retorna)
		return $strJsPag;
	else
		$objCtrlSmarty->assign("JS_PAGE",$strJsPag);
}

if($class != "index" && $class != "login" && $class != "ajax"){
	require_once PASTA_ADMIN.$class.".php";
	$objView = new $class();
	
	//definição da estrutura do admin <cabecalho, corpo e rodape>
	$objCtrlSmarty->assign("ESTRUTURA",$objCtrlSmarty->fetch(TPLS_FILE."admin/adminEstrutura.tpl"));
	//ultima coisa que deve ter no arquivo, serve para imprimir a tela
	$objCtrlSmarty->display(TPLS_FILE."index.tpl");
}

?>